package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.RegionForm;
import ru.housewife.form.WareForm;
import ru.housewife.form.WareRegionPriceForm;
import ru.housewife.model.WareRegionPrice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class GetWaresPricesForWaresInRegion implements HibernateAction<List<WareRegionPriceForm>> {

    private static final int MAX_IDS_IN_SELECT = 100;

    private RegionForm region;

    private List<Long> wareIds;

    public GetWaresPricesForWaresInRegion(RegionForm region, List<Long> wareIds) {
        this.region = region;
        this.wareIds = wareIds;
    }

    @Override
    public List<WareRegionPriceForm> execute(Session session) {
        if (wareIds.size() <= MAX_IDS_IN_SELECT) {
            return getWaresRegionPrices(session, wareIds);
        } else {
            int pageCnt = wareIds.size() / MAX_IDS_IN_SELECT + 1;
            List<WareRegionPriceForm> result = new ArrayList<WareRegionPriceForm>(wareIds.size());
            for (int page = 0; page < pageCnt; page++) {
                int fromIndex = page * MAX_IDS_IN_SELECT;
                int toIndex = fromIndex + MAX_IDS_IN_SELECT;
                toIndex = (toIndex > wareIds.size()) ? wareIds.size() : toIndex;

                result.addAll(getWaresRegionPrices(session, wareIds.subList(fromIndex, toIndex)));
            }
            return result;
        }
    }

    private List<WareRegionPriceForm> getWaresRegionPrices(Session session, List<Long> wareIds) {
        if (wareIds.isEmpty()) {
            return Collections.emptyList();
        }
        CacheManager cacheManager = CacheManager.getInstance();

        Query q = session.createQuery("select wp from WareRegionPrice wp where wp.region.id=:regionId and wp.ware.id in (:wareIds)");
        q.setLong("regionId", region.getId());
        q.setParameterList("wareIds", wareIds);
        List<WareRegionPrice> prices = q.list();
        List<WareRegionPriceForm> result = new ArrayList<WareRegionPriceForm>(wareIds.size());
        for (WareRegionPrice price : prices) {
            WareForm wareForm = cacheManager.getWareForm(price.getWareId());
            if (wareForm != null) {
                result.add(new WareRegionPriceForm(wareForm, region, price.getPrice()));
            } else {
                // TODO: ALARM
            }
        }
        return result;
    }
}
